import React from "react"
import { Button, Image, Input, View } from "@tarojs/components"
import { Popup } from "@taroify/core"
import { useSetState } from "@/utils/hooks"
// import clsx from "clsx"
import { useAppDispatch, useAppSelector } from "@/store/hook"
import { patchExtra, refreshUserInfo } from "@/store/actions/auth"
import Taro from "@tarojs/taro"
// import styles from "./index.module.scss"
import { updateUserAvatarAndNickname, uploadV4 } from "@/apis/yikao-community"
import { requestIsFullfilled } from "@/utils/request"
import Icon from "@/components/GpFontIcon"

type IState = {
  avatarUrl: string
  nickName: string
}
/**
 * @component 头像昵称授权弹窗
 * @description 授权头像昵称：当用户授权手机号却没有配置头像昵称时，用户评论或发笔记会跳一次弹窗，用户如果再次取消不影响他发笔记发内容，下次再点接着跳弹窗
 */
export default function AuthModal() {
  const dispatch = useAppDispatch()
  const authExtra = useAppSelector(state => state.auth.extra)
  const [state, setState] = useSetState<IState>({
    avatarUrl: "",
    nickName: ""
  })
  async function handleConfirm() {
    if (!state.avatarUrl) {
      Taro.showToast({
        title: "请上传头像",
        icon: "none"
      })
      return
    }
    if (!state.nickName) {
      Taro.showToast({
        title: "请填写昵称",
        icon: "none"
      })
      return
    }
    Taro.showLoading({ title: "上传头像中" })
    try {
      let _avatar = ""
      const uploadRes = await uploadV4(state.avatarUrl)
      if (uploadRes.data) {
        const resData = JSON.parse(uploadRes.data)
        if (resData.success) {
          _avatar = resData.data.image
        }
      }
      Taro.hideLoading()
      if (!_avatar) {
        Taro.showToast({
          title: "上传头像失败",
          icon: "none"
        })
        return
      }
      Taro.showLoading({ title: "上传资料中" })
      const res = await updateUserAvatarAndNickname({
        headImage: _avatar,
        nickName: state.nickName
      })
      Taro.hideLoading()
      if (requestIsFullfilled(res)) {
        await dispatch(refreshUserInfo() as any)
        Taro.showToast({
          title: "更新资料成功",
          icon: "none"
        })
        let cb: INullable<IFn> = null
        if (typeof authExtra.authModalConfirmFn === "function") {
          cb = authExtra.authModalConfirmFn
        }
        close()
        cb && cb()
        return
      }
      Taro.showToast({
        title: "上传资料失败",
        icon: "none"
      })
    } catch (error) {
      console.log("更新资料捕获到错误了", error)
      Taro.hideLoading()
      Taro.showToast({
        title: "更新资料失败",
        icon: "none"
      })
    }
  }
  function handleCancel() {
    let cb: INullable<IFn> = null
    if (typeof authExtra.authModalCancelFn === "function") {
      cb = authExtra.authModalCancelFn
    }
    close({
      authModalCanceled: true
    })
    cb && cb()
  }
  function close(extra?: IAuthStore["extra"]) {
    setState({
      avatarUrl: "",
      nickName: ""
    })
    dispatch(
      patchExtra({
        showAuthModal: false,
        authModalCancelFn: null,
        authModalConfirmFn: null,
        ...extra
      })
    )
  }
  return (
    <Popup
      open={authExtra.showAuthModal}
      style={{
        background: "none"
      }}
    >
      <View
        style={{
          width: 311,
          boxSizing: "border-box",
          background: "#fff",
          borderRadius: 16,
          paddingTop: 24,
          paddingLeft: 16,
          paddingRight: 16,
          paddingBottom: 16
        }}
      >
        <View
          style={{
            color: "#333333",
            fontWeight: 500,
            fontSize: 18,
            textAlign: "center"
          }}
        >
          请完善头像和昵称信息
        </View>
        <View
          style={{
            color: "#333333",
            fontWeight: "normal",
            fontSize: 14,
            textAlign: "center",
            marginTop: 9
          }}
        >
          打造属于你的社区形象！
        </View>
        <View
          style={{
            display: "flex",
            flexDirection: "row",
            marginTop: 32
          }}
        >
          <View
            style={{
              color: "#333333",
              fontSize: 14
            }}
          >
            上传头像：
          </View>
          <View
            style={{
              width: 90,
              height: 90,
              marginLeft: 25,
              backgroundColor: "#f7f7f7",
              borderRadius: "100%",
              overflow: "hidden",
              boxSizing: "border-box"
            }}
          >
            <Button
              style={{
                border: "none",
                backgroundColor: "inherit",
                outline: "none",
                padding: 0,
                display: "flex",
                flexDirection: "row",
                justifyContent: "center",
                alignItems: "center",
                width: "100%",
                height: "100%",
                color: "#666666",
                fontSize: 32
              }}
              openType="chooseAvatar"
              onChooseavatar={ev => setState({ avatarUrl: ev.detail.avatarUrl })}
            >
              {state.avatarUrl ? (
                <Image
                  src={state.avatarUrl}
                  style={{
                    width: 90,
                    height: 90,
                    objectFit: "cover",
                    display: "block",
                    borderRadius: "100%"
                  }}
                />
              ) : (
                <Icon icon="icon-tianjia" color="#999999" size={48} />
              )}
            </Button>
          </View>
        </View>
        <View
          style={{
            display: "flex",
            flexDirection: "row",
            boxSizing: "border-box",
            marginTop: 16,
            alignItems: "center"
          }}
        >
          <View
            style={{
              color: "#333333",
              fontSize: 14
            }}
          >
            昵称：
          </View>
          <View
            style={{
              borderBottom: "1px solid #f2f2f2",
              boxSizing: "border-box"
            }}
          >
            <Input
              type="nickname"
              style={{
                fontSize: 14,
                color: "#333333",
                padding: 8,
                textAlign: "center",
                width: 170
              }}
              placeholder="请输入你的昵称"
              placeholderStyle="color: #bbbbbb;"
              onInput={ev => {
                console.info("昵称输入框输入事件触发了", ev.detail.value)
                setState({ nickName: ev.detail.value })
                return ev.detail.value
              }}
            />
          </View>
        </View>
        <View
          style={{
            display: "flex",
            flexDirection: "row",
            justifyContent: "center",
            marginTop: 40
          }}
        >
          <View
            style={{
              width: 120,
              height: 38,
              borderRadius: 22,
              display: "flex",
              flexDirection: "row",
              justifyContent: "center",
              alignItems: "center",
              boxSizing: "border-box",
              fontSize: 16,
              background: "#f1f5f9",
              color: "#666666",
              marginRight: 16
            }}
            onClick={handleCancel}
          >
            取消
          </View>
          <View
            style={{
              width: 120,
              height: 38,
              borderRadius: 22,
              display: "flex",
              flexDirection: "row",
              justifyContent: "center",
              alignItems: "center",
              boxSizing: "border-box",
              fontSize: 16,
              background: "#5278FD",
              color: "#ffffff"
            }}
            onClick={handleConfirm}
          >
            确认
          </View>
        </View>
      </View>
    </Popup>
  )
  /**
   * skyline模式下 组件的className样式不生效, 需要使用style样式(巨坑)
   * 下面代码暂时保留
   */
  // return (
  //   <Popup
  //     open={authExtra.showAuthModal}
  //     style={{
  //       background: "none"
  //     }}
  //   >
  //     <View className={styles.box}>
  //       <View className={styles.title}>请完善头像和昵称信息</View>
  //       <View className={styles.desc}>打造属于你的社区形象！</View>
  //       <View className={styles.avatarControl}>
  //         <View className={styles.controlLabel}>上传头像：</View>
  //         <View className={styles.avatarWrap}>
  //           <Button
  //             className={styles.avatarBtn}
  //             openType="chooseAvatar"
  //             onChooseavatar={ev => setState({ avatarUrl: ev.detail.avatarUrl })}
  //           >
  //             {state.avatarUrl ? (
  //               <Image src={state.avatarUrl} className={styles.avatar} />
  //             ) : (
  //               <Plus color="#999999" />
  //             )}
  //           </Button>
  //         </View>
  //       </View>
  //       <View className={styles.nicknameControl}>
  //         <View className={styles.controlLabel}>昵称：</View>
  //         <View className={styles.avatarWrap}>
  //           <Input
  //             type="nickname"
  //             className={styles.nicknameInput}
  //             placeholder="请输入你的昵称"
  //             placeholderClass={styles.nicknamePlaceholder}
  //             value={state.nickName}
  //             onInput={ev => setState({ nickName: ev.detail.value })}
  //           />
  //         </View>
  //       </View>
  //       <View className={styles.actions}>
  //         <View className={clsx(styles.action, styles.cancel)} onClick={handleCancel}>
  //           取消
  //         </View>
  //         <View className={clsx(styles.action, styles.confirm)} onClick={handleConfirm}>
  //           确认
  //         </View>
  //       </View>
  //     </View>
  //   </Popup>
  // )
}
